package com.zhl.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhl.cache.OldMyCacheManager;
import com.zhl.mapper.UserMapper;
import com.zhl.model.User;

@Service
public class OldUserService {
	@Autowired
	private UserMapper userMapper;
	private OldMyCacheManager<User> cacheManager;
	
	public OldUserService(){
		//构造一个缓存管理器
		cacheManager = new OldMyCacheManager<User>();
	}
	
	public User getUserByName(String name){
		User result = cacheManager.getValue(name);
		if(result != null){
			System.out.println("从缓存中获得结果："+name);
			//如果缓存中存在结果，直接返回缓存结果
			return result;
		}
		//否则到数据库中查询
		result = getFromDB(name);
		if(result != null){
			cacheManager.addOrUpdateCache(name, result);
		}
		return result;
	}
	
	public void reload(){
		cacheManager.evictCache();
	}
	
	private User getFromDB(String name){
		System.out.println("从数据库中获得结果："+name);
		User user = userMapper.findByName(name);
		return user;
	}
	

	
}
